const jwt = require("jsonwebtoken");
const { createUser, findUsers } = require("../service/user.server");
const { resObj } = require("../utils/index");
const { JWT_SECRET } = require("../config/config.base");
class UserConlltroller {
  async register(ctx) {
    try {
      const { username } = ctx.request.body;
      await createUser(ctx.request.body);
      ctx.body = resObj.success({ username }, "注册成功");
    } catch (error) {
      ctx.body = resObj.error(`参数错误: ${error}`);
    }
  }
  async login(ctx) {
    try {
      const { user } = ctx;
      delete user.password;
      const token = jwt.sign(user, JWT_SECRET);
      user.token = token;
      ctx.body = resObj.success(user, "登录成功");
    } catch (error) {
      ctx.body = resObj.error(`参数错误: ${error}`);
    }
  }
  async getUsers(ctx) {
    try {
      const users = await findUsers(ctx.request.query, !!ctx.user.isAdmin);
      ctx.body = resObj.success(users, "查询成功");
    } catch (error) {
      ctx.body = resObj.error("查询失败");
    }
  }
}
module.exports = new UserConlltroller();
